package handler

import (
	"bufio"
	"dlm/internal/db"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// 登录认证
func Login(c *gin.Context) {
	var req struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "参数错误"})
		return
	}

	user, err := db.DB.GetUserByUsername(req.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "服务器错误"})
		return
	}
	if user == nil || user.Password != req.Password {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "用户名或密码错误"})
		return
	}

	expirationTime := time.Now().Add(2 * time.Hour)

	// 创建claims
	claims := &jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(expirationTime),
		Subject:   user.Username,
	}

	// 签名生成Token（实际使用时需替换为安全的密钥）
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte("your-secret-key"))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "生成Token失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success":   true,
		"token":     tokenString,
		"expiresIn": int(expirationTime.Sub(time.Now()).Seconds()), // 过期时间（秒）
	})
}

// GetAllNamespaces 从配置文件读取命名空间（替代数据库查询）
func GetAllNamespaces(c *gin.Context) {
	// 读取 configs/namespaces.txt 文件
	namespaces, err := getNamespacesFromFile()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("读取命名空间配置失败: %v", err)})
		return
	}
	c.JSON(http.StatusOK, namespaces)
}

// GetStorageData 获取存储数据（只显示每个 pod 的最新记录）
func GetStorageData(c *gin.Context) {
	namespace := c.Query("namespace")
	var args []interface{}

	query := `
		SELECT t1.namespace, t1.app, t1.pvc, t1.total_size, t1.used_size, t1.available_size, t1.usage_percent, t1.created_at
		FROM storage t1
		INNER JOIN (
			SELECT pvc, MAX(created_at) as max_created_at
			FROM storage
			` + getWhereClause(namespace, &args) + `  -- 子查询条件（命名空间筛选）
			GROUP BY pvc
		) t2 ON t1.pvc = t2.pvc
		AND t1.created_at = t2.max_created_at
	`

	rows, err := db.DB.Query(query, args...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("查询数据失败: %v", err)})
		return
	}
	defer rows.Close()

	var dataList []db.StorageData
	for rows.Next() {
		var data db.StorageData
		if err := rows.Scan(
			&data.Namespace,
			&data.App,
			&data.PVCName,
			&data.TotalSize,
			&data.UsedSize,
			&data.AvailableSize,
			&data.UsagePercent,
			&data.CreatedAt,
		); err != nil {
			fmt.Printf("扫描数据行失败: %v\n", err)
			continue
		}
		dataList = append(dataList, data)
	}

	if err = rows.Err(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("遍历数据失败: %v", err)})
		return
	}

	c.JSON(http.StatusOK, dataList)
}

// getWhereClause 生成子查询的 WHERE 条件，并添加参数
func getWhereClause(namespace string, args *[]interface{}) string {
	if namespace != "" {
		*args = append(*args, namespace) // 统一管理参数，避免重复
		return "WHERE namespace = ?"
	}
	return ""
}

// GetStorageTrend 查询存储使用率趋势（保持不变）
func GetStorageTrend(c *gin.Context) {
	namespace := c.Query("namespace")
	if namespace == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "namespace 参数必填"})
		return
	}

	query := `
		SELECT 
			DATE_FORMAT(created_at, '%Y-%m-%d %H:00') as time,
			AVG(CAST(REPLACE(usage_percent, '%', '') AS DECIMAL(5,2))) as avg_usage
		FROM storage
		WHERE namespace = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
		GROUP BY time
		ORDER BY time ASC
	`
	rows, err := db.DB.DB.Query(query, namespace)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("数据库查询失败: %v", err)})
		return
	}
	defer rows.Close()

	var trend []map[string]interface{}
	for rows.Next() {
		var t string
		var usage float64
		if err := rows.Scan(&t, &usage); err != nil {
			fmt.Printf("扫描趋势数据失败: %v\n", err)
			continue
		}
		trend = append(trend, map[string]interface{}{"time": t, "usage": usage})
	}

	if err = rows.Err(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("遍历趋势数据失败: %v", err)})
		return
	}

	c.JSON(http.StatusOK, trend)
}

// 辅助函数：从配置文件读取命名空间（与 k8s 包的逻辑一致）
func getNamespacesFromFile() ([]string, error) {
	// 读取项目根目录/configs/namespaces.txt
	path := filepath.Join("configs", "namespaces.txt")
	file, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("文件不存在或无法打开（路径：%s）：%v", path, err)
	}
	defer file.Close()

	var namespaces []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		ns := strings.TrimSpace(scanner.Text())
		if ns != "" { // 跳过空行
			namespaces = append(namespaces, ns)
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("读取文件内容失败：%v", err)
	}
	return namespaces, nil
}
